//
//  QXHomeVC.m
//  QXBlog
//
//  Created by QinXin on 15/7/5.
//  Copyright © 2015年 labi3285_Lab. All rights reserved.
//

#import "QXHomeVC.h"
#import "QXNetworking.h"

#import "QXAccount.h"
#import "QXUser.h"
#import "QXStatus.h"

#import <SVProgressHUD/SVProgressHUD.h>

@interface QXHomeVC ()
@property (nonatomic, strong) NSMutableArray *localDataListCache;
@property (nonatomic, strong) NSMutableArray *data;
@end

@implementation QXHomeVC

- (NSMutableArray *)data {
    if (!_data) {
        _data = [self loadLocalData];
    }
    return _data;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"UITableViewCell"];
    
    self.localDataListCache = [[NSUserDefaults standardUserDefaults] objectForKey:@"home_timeline_localDataListCache"];
    
    if (self.data.count == 0) {
        [self loadWebDataWithSinceId:0 MaxId:0];
    }
}

//- (void)loadNew {
//    
//    [self.data addObjectsFromArray: [self loadWebDataWithSinceId:0 MaxId:0]];
//    [self.tableView reloadData];
//    
//    NSLog(@"%@", self.data);
//
//}
//
//- (void)loadOld {
//    
//}

- (NSMutableArray *)loadLocalData {
    NSMutableArray *marr = [NSMutableArray array];
    for (int i = (int)self.localDataListCache.count - 1; i >= 0; i--) {
        NSInteger identifier = [self.localDataListCache[i] integerValue];
        QXStatus *status = [QXStatus unAchivedWithIdStr:[NSString stringWithFormat:@"%ld", identifier]];
        [marr addObject:status];
    }
    return marr;
}


- (void)loadWebDataWithSinceId:(int)sinceId MaxId:(int)maxId {
    
    NSDictionary *params = @{
                             // 采用OAuth授权方式为必填参数
                             @"access_token": [QXAccount sharedAccount].access_token,
                             // 返回ID比since_id大的微博（即比since_id时间晚的微博），默认为0
                             @"since_id": @(sinceId),
                             // 返回ID小于或等于max_id的微博，默认为0
                             @"max_id": @(maxId),
                             // 单页返回的记录条数，最大不超过100，默认为20
                             @"count": @(10),
                             // 返回结果的页码
                             @"page": @(1),
                             // 是否只获取当前应用的数据。0为否（所有数据），1为是（仅当前应用），默认为0
                             @"base_app": @(0),
                             // 过滤类型ID，0：全部、1：原创、2：图片、3：视频、4：音乐，默认为0
                             @"feature": @(0),
                             // 返回值中user字段开关，0：返回完整user字段、1：user字段仅返回user_id，默认为0
                             @"trim_user": @(0),
                             };
    
    
    [SVProgressHUD show];
    
    self.localDataListCache = [NSMutableArray array];
    
    [[QXNetworking sharedNetworking] GET:@"2/statuses/home_timeline.json" parameters:params success:^(NSURLSessionDataTask *task, id dic) {
        
        for (NSDictionary *dic1 in dic[@"statuses"]) {
            QXStatus *status = [QXStatus statusWithDic:dic1];
            [status achiveToIdPath];
                        
            [self.localDataListCache addObject: status.idstr];
            [self.data addObject:status];
        }
        
        [self.tableView reloadData];

        
         [[NSUserDefaults standardUserDefaults] setObject:self.localDataListCache forKey:@"home_timeline_localDataListCache"];
        
        [SVProgressHUD dismiss];
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"加载失败"];
        [SVProgressHUD dismiss];
    }];
    
}


#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.data.count;
}

- (UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell"];
    QXStatus *status = self.data[indexPath.row];
    cell.textLabel.text = status.text;
    return cell;
}

@end
